<script>
import { LoadingControl } from '@/utils'
export default {
  name: 'StatusHandle',
  props: {
    status: String,
    get: {
      type: Function,
    },
    loading: {
      type: Object,
      default() {
        return {
          type: 'normal',
          color: '#000',
          size: 25,
        }
      },
    },
    block: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      inner: {
        status: '',
        error: '',
      },
    }
  },
  created() {
    if (this.status) {
      this.inner.status = this.status
    }
    this.getData()
  },
  watch: {
    status(v) {
      this.inner.status = v
    },
  },
  methods: {
    getData() {
      const { inner, get } = this
      if (get) {
        LoadingControl({
          call: get,
          change: ({ status }) => {
            this.inner.status = status
          },
        }).catch((e) => {
          this.inner.error = typeof e === 'object' ? e.message : e
        })
      } else {
        this.$nextTick(() => {
          if (!['loading', 'success'].includes(inner.status)) {
            this.$emit('retry')
          }
        })
      }
    },
    getLoading() {
      const { $slots, loading } = this
      return $slots.loading || <a-spin />
    },
  },
  render() {
    const { inner, block } = this
    switch (inner.status) {
      case '':
      case 'init':
      case 'loading':
        return (
          <div class={['loading-box flex-column', inner.status, block ? 'block align ' : '']}>{this.getLoading()}</div>
        )
      case 'success':
        return this.$slots ? this.$slots.default : null
      case 'error':
      default:
        if (block) {
          return (
            <a-empty
              image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original"
              description={inner.error}
            >
              <a-button onClick={this.getData} type="primary">
                点我重试
              </a-button>
            </a-empty>
          )
        } else {
          return (
            <button class="retry" onClick={this.getData}>
              {inner.error}
              {inner.error ? ',' : ''}点我重试
            </button>
          )
        }
    }
  },
}
</script>
<style lang="less">
.loading-box {
  &.block {
    padding: 0.15rem;
    width: 100%;
  }
}
.retry {
  font-size: 0.14rem;
  line-height: 0.25rem;
  text-align: center;
  &.block {
    padding: 0.15rem;
    width: 100%;
  }
}
</style>
